package com.numberone.master.common.yunzhanghu;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.numberone.master.common.yunzhanghu.bean.OrderBean;
import com.numberone.master.common.yunzhanghu.bean.QueryAmountBean;
import com.numberone.master.common.yunzhanghu.bean.QueryOrderBean;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import com.alibaba.fastjson.JSONObject;
import com.numberone.master.common.exception.BizException;
import com.numberone.master.common.http.HttpClientUtil;
import com.numberone.master.common.utils.StringUtils;

/**
 * 云账户提现工具类
 */
public class TixianUtil {
	//商户代码
	private static final String dealer_id = "01637680";
	//代征主体
	private static final String broker_id = "yiyun73";
	//deskey
	private static final String deskey="22kR1XgtB3O3zUPHo9gXydK1";
	//appKey
	private static final String appKey="XZ3oVGbb83QreuJ93q7F3PNTM6t4N7AQ";

	private static final String baseUrl="https://api-jiesuan.yunzhanghu.com/";

	/**
	 * 提现方法
	 * @param order_id
	 * @param real_name
	 * @param card_no
	 * @param id_card
	 * @param pay
	 * @param pay_remark
	 */
	public static void TiXian(String order_id,String real_name,
			String card_no,String id_card,String pay,String pay_remark){
		
			OrderBean bean = new OrderBean(order_id,dealer_id,broker_id,real_name,card_no,
					id_card,pay,pay_remark,pay_remark);
			 String orderJson = JSONObject.toJSON(bean).toString();
			 String payUrl=baseUrl+"api/payment/v1/order-realtime";

			try {
				byte[] enc = DesBase.TripleDesEncrypt(orderJson.getBytes("utf-8"), deskey.getBytes("utf-8"));
				
				byte[] enc64 = Base64.encodeBase64(enc);
				
				String data=new String (enc64);
				
				String param="data="+data;
				
				param+="&mess="+StringUtils.getRandomNumberString(6);
				String timestamp=String.valueOf(System.currentTimeMillis());
				timestamp=timestamp.substring(0, timestamp.length()-3);
					
				param+="&timestamp="+timestamp;
				
				String signmessage=param+"&key="+appKey;
				
				String sign=HmacSha256.sha256HMAC(signmessage,appKey);
				
				param+="&sign="+sign;
				
				param+="&sign_type=sha256";
				param=URLEncoder.encode(param);

				param=param.replace("%3D", "=").replace("%26", "&");
				
				Map<String, Object> map = HttpClientUtil.getTokenByPost(payUrl,param,dealer_id);
				System.out.println(map);
				Gson gson = new Gson();
				Map<String, Object> tokenData = gson.fromJson(map.get("tokenData").toString(), map.getClass());
				String code=tokenData.get("code").toString();
				if(code!=null){
					if(code.equals("2027")){
						throw new BizException("1","当前提现人数过多，请稍后再试");
					}else if(!code.equals("0000")){
						throw new BizException("1",tokenData.get("message").toString());
					}
					
				}else{
					throw new BizException("1","提现请求发送失败");
				}
				
			
			
			} catch (Exception e) {
				e.printStackTrace();
				throw new BizException("1",e.getMessage());
				// TODO Auto-generated catch block
			}
		
	}



	/**
	 * 查询订单
	 * @param orderNo
	 * @param channel
	 * @return
	 */
	public static Map<String,Object> queryOrder(String orderNo,String channel){
		String queryUrl=baseUrl+"api/payment/v1/query-realtime-order";

		Map<String, Object> result=null;
		QueryOrderBean queryOrderBean=new QueryOrderBean();
		queryOrderBean.setOrder_id(orderNo);
		queryOrderBean.setChannel(channel);
		String jsonStr=JSONObject.toJSONString(queryOrderBean);
		try {
			byte[] dec = DesBase.TripleDesEncrypt(jsonStr.getBytes("utf-8"), deskey.getBytes("utf-8"));
			byte[] base = Base64.encodeBase64(dec);

			String data=new String(base);
			String param="data="+data;
			param+="&mess="+StringUtils.getRandomNumberString(6);
			String timestamp=String.valueOf(System.currentTimeMillis());
			timestamp=timestamp.substring(0, timestamp.length()-3);

			param+="&timestamp="+timestamp;

			String signmessage=param+"&key="+appKey;

			String sign=HmacSha256.sha256HMAC(signmessage,appKey);

			param+="&sign="+sign;

			param+="&sign_type=sha256";
			param=URLEncoder.encode(param);

			param=param.replace("%3D", "=").replace("%26", "&");

			result=HttpClientUtil.getTokenByGet(queryUrl,param,dealer_id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	//查询云账户余额，如果不足则返回对应提示
	public static void queryAccountAmount(String tranAmount) {
		QueryAmountBean amountBean=new QueryAmountBean();
		amountBean.setDealer_id(dealer_id);
		String jsonStr = JSONObject.toJSONString(amountBean);

		String url=baseUrl+"api/payment/v1/query-accounts";
		try {
			byte[] dec = DesBase.TripleDesEncrypt(jsonStr.getBytes("utf-8"), deskey.getBytes("utf-8"));
			byte[] base = Base64.encodeBase64(dec);

			String data=new String(base);
			String param="data="+data;
			param+="&mess="+StringUtils.getRandomNumberString(6);
			String timestamp=String.valueOf(System.currentTimeMillis());
			timestamp=timestamp.substring(0, timestamp.length()-3);

			param+="&timestamp="+timestamp;

			String signmessage=param+"&key="+appKey;

			String sign=HmacSha256.sha256HMAC(signmessage,appKey);

			param+="&sign="+sign;

			param+="&sign_type=sha256";
			param=URLEncoder.encode(param);

			param=param.replace("%3D", "=").replace("%26", "&");
			System.out.println(param);
			Map<String, Object> result = HttpClientUtil.getTokenByGet(url, param, dealer_id);
			String entityStr=result.get("tokenData").toString();
			if (entityStr != null) {
				Gson gson = new Gson();
				Map<String,Object> resultMap = gson.fromJson(entityStr, Map.class);
				System.out.println(resultMap);
				BigDecimal totalBalance=new BigDecimal("0.00");
				if ("0000".equals(resultMap.get("code"))){
					Map<String,Object> map= (Map<String, Object>) resultMap.get("data");
					List infoslist= (List) map.get("dealer_infos");
					for (int i = 0; i < infoslist.size(); i++) {
						Map<String,Object> objectMap= (Map<String, Object>) infoslist.get(i);
						if (objectMap.get("broker_id").equals(broker_id)){
							totalBalance=totalBalance.add(new BigDecimal(objectMap.get("alipay_balance").toString()));
							totalBalance=totalBalance.add(new BigDecimal(objectMap.get("bank_card_balance").toString()));
							totalBalance=totalBalance.add(new BigDecimal(objectMap.get("wxpay_balance").toString()));
						}
					}
					if (new BigDecimal(tranAmount).compareTo(totalBalance)==1){
						throw  new BizException("1","当前提现人数过多，请稍后再试");
					}
				}else {

					throw  new BizException("1","系统异常");
				}

			} else {
				throw  new BizException("1","系统异常");
			}
			} catch (Exception e) {
				throw new BizException("1",e.getMessage());
			}finally {

			}

	}
	public static void main(String[] args) {

		//System.out.println(TixianUtil.queryOrder("WLWK-2019030613405592218","银行卡"));
		//queryAccountAmount("500");
	}

}
